import { ref } from "vue";

export default function useInterval(defaultTime: number, task: () => void) {
  const isAction = ref(false);
  const time = ref(defaultTime);
  const copyTime = ref(defaultTime);
  const timer = ref(null);

  const start = () => {
    if (timer.value) return;
    if (!isAction.value) return;
    copyTime.value = time.value;
    // @ts-ignore
    timer.value = setInterval(() => {
      if (time.value > 0) time.value--;
      if (time.value <= 0) {
        stop();
        task && task();
      }
    }, 1000);
  };

  const stop = () => {
    time.value = copyTime.value;
    // @ts-ignore
    clearInterval(timer.value);
    timer.value = null;
  };

  return {
    isAction,
    time,
    start,
    stop,
  };
}
